﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TriaServer.Enum;
using TriaServer.Model;

namespace TriaServer
{
    public partial class Form1 : Form
    {
        TriaService triaService;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //检查是否多开
            string processName = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(processName);
            //如果该数组长度大于1，说明多次运行
            if (processes.Length > 1)
            {
                MessageBox.Show("程序已运行，不能再次打开！");
                Environment.Exit(1);
            }

            FormHide();
            triaService = TriaService.getInstance();
            triaService.MesgNotificationEvent += AppendText;
            triaService.TriaStateEvent += TriaStateEvent;
            triaService.Init();
            if (triaService.TriaConfig != null)
                TxtRefresh();
        }

        private void TriaStateEvent(bool obj)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                if (obj)
                    pbTriaState.BackColor = Color.Green;
                else
                    pbTriaState.BackColor = Color.Red;
            }));
        }

        private void TxtRefresh()
        {
            txtIP.Text = triaService.TriaConfig.Tria_Ip;
            txtPort.Text = triaService.TriaConfig.Tria_Port.ToString();
            txtLogicLength.Text = triaService.TriaConfig.Logic_Length.ToString();
            txtPointPosition.Text = triaService.TriaConfig.Point_Position.ToString();
            txtPointLength.Text = triaService.TriaConfig.Point_Length.ToString();
            txtSequencePosition.Text = triaService.TriaConfig.Sequence_Position.ToString();
            txtSequenceLength.Text = triaService.TriaConfig.Sequence_Length.ToString();
            txtCarBodyNoPosition.Text = triaService.TriaConfig.Car_Body_No_Position.ToString();
            txtCarBodyNoLength.Text = triaService.TriaConfig.Car_Body_No_Length.ToString();
            txtVinNoPosition.Text = triaService.TriaConfig.Vin_No_Position.ToString();
            txtVinNoLength.Text = triaService.TriaConfig.Vin_No_Length.ToString();
            txtCarModelCodePosition.Text = triaService.TriaConfig.Car_Model_Code_Position.ToString();
            txtCarModelCodeLength.Text = triaService.TriaConfig.Car_Model_Code_Length.ToString();
            //txtPartsCodePosition.Text = triaService.TriaConfig.TriaIp;
            //txtPartsCodeLength.Text = triaService.TriaConfig.TriaIp;
            txtPartsCode1Position.Text = triaService.TriaConfig.Parts_Code1_Position.ToString();
            txtPartsCode1Length.Text = triaService.TriaConfig.Parts_Code1_Length.ToString();
            txtPartsCode2Position.Text = triaService.TriaConfig.Parts_Code2_Position.ToString();
            txtPartsCode2Length.Text = triaService.TriaConfig.Parts_Code2_Length.ToString();
            //txtPartsCodePosition.Text = triaService.TriaConfig.TriaIp;
            //txtPartsCodeLength.Text = triaService.TriaConfig.TriaIp;
        }

        /// <summary>
        /// 将收文或发文字符串处理后加入文本接收区
        /// </summary>
        /// <param name="mesg"></param>
        /// <param name="messageType"></param>
        private void AppendText(string mesg, MessageType messageType)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                if (messageType == MessageType.Info)
                    AppendTextColorful(ref this.txtMesg, mesg, Color.Black, true);
                else if (messageType == MessageType.Error)
                    AppendTextColorful(ref this.txtMesg, mesg, Color.Red, true);
                else if (messageType == MessageType.warning)
                    AppendTextColorful(ref this.txtMesg, mesg, Color.OrangeRed, true);
            }));
        }

        /// <summary>
        /// 富文本框格式化方法
        /// </summary>
        /// <param name="rtBox">富文本框</param>
        /// <param name="addtext">添加文本内容</param>
        /// <param name="color">当前添加文本显示颜色</param>
        /// <param name="IsaddNewLine">是否换行</param>
        private void AppendTextColorful(ref RichTextBox rtBox, string addtext, Color color, bool IsaddNewLine)
        {
            if (IsaddNewLine)
            {
                addtext += Environment.NewLine;
            }
            rtBox.SelectionStart = rtBox.TextLength;
            rtBox.SelectionLength = 0;
            rtBox.SelectionColor = color;
            rtBox.AppendText(DateTime.Now.ToString() + "  " + addtext);
            rtBox.SelectionColor = rtBox.ForeColor;

            if (rtBox.Lines.Length > 5000)
            {
                rtBox.Text = rtBox.Text.Remove(0, rtBox.GetFirstCharIndexFromLine(3000));
            }
            rtBox.Focus();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            FormHide();
        }

        private void show_Click(object sender, EventArgs e)
        {
            FormShow();
        }

        private void exit_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            FormShow();

        }

        private void FormHide()
        {
            try
            {
                this.Hide();
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon1.Visible = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        private void FormShow()
        {
            //还原窗体显示    
            this.WindowState = FormWindowState.Normal;
            //激活窗体并给予它焦点
            this.Activate();
            this.Show();
            //任务栏区显示图标
            this.ShowInTaskbar = true;
            //托盘区图标隐藏
            notifyIcon1.Visible = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (triaService.TriaConfig == null)
                    triaService.TriaConfig = new TriaConfigModel();
                triaService.TriaConfig.Tria_Ip = txtIP.Text;
                triaService.TriaConfig.Tria_Port = int.Parse(txtPort.Text);
                triaService.TriaConfig.Logic_Length = int.Parse(txtLogicLength.Text);
                triaService.TriaConfig.Point_Position = int.Parse(txtPointPosition.Text);
                triaService.TriaConfig.Point_Length = int.Parse(txtPointLength.Text);
                triaService.TriaConfig.Sequence_Position = int.Parse(txtSequencePosition.Text);
                triaService.TriaConfig.Sequence_Length = int.Parse(txtSequenceLength.Text);
                triaService.TriaConfig.Car_Body_No_Position = int.Parse(txtCarBodyNoPosition.Text);
                triaService.TriaConfig.Car_Body_No_Length = int.Parse(txtCarBodyNoLength.Text);
                triaService.TriaConfig.Vin_No_Position = int.Parse(txtVinNoPosition.Text);
                triaService.TriaConfig.Vin_No_Length = int.Parse(txtVinNoLength.Text);
                triaService.TriaConfig.Car_Model_Code_Position = int.Parse(txtCarModelCodePosition.Text);
                triaService.TriaConfig.Car_Model_Code_Length = int.Parse(txtCarModelCodeLength.Text);
                //triaService.TriaConfig.PartsCodePosition = int.Parse(txtPartsCodePosition.Text);
                //triaService.TriaConfig.PartsCodeLength = int.Parse(txtPartsCodeLength.Text);
                triaService.TriaConfig.Parts_Code1_Position = int.Parse(txtPartsCode1Position.Text);
                triaService.TriaConfig.Parts_Code1_Length = int.Parse(txtPartsCode1Length.Text);
                triaService.TriaConfig.Parts_Code2_Position = int.Parse(txtPartsCode2Position.Text);
                triaService.TriaConfig.Parts_Code2_Length = int.Parse(txtPartsCode2Length.Text);
                //triaService.TriaConfig.PartsCodePosition = int.Parse(txtPartsCodePosition.Text);
                //triaService.TriaConfig.PartsCodeLength = int.Parse(txtPartsCodeLength.Text);
                var result = triaService.SaveConfig(triaService.TriaConfig);
                if (result)
                    MessageBox.Show("参数保存成功！");
                else
                    MessageBox.Show("参数保存失败！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"参数保存失败!{ex.Message}");
            }
        }
    }
}
